//
//  FDDToast.m
//  AlertToastHUD
//
//  Created by caiqiang on 2018/11/30.
//  Copyright © 2020 wenwen. All rights reserved.
//

#import "FDDToast.h"
#import <Masonry.h>

NSNotificationName const FDDToastWillShowNotification    = @"FDDToastWillShowNotification";
NSNotificationName const FDDToastDidShowNotification     = @"FDDToastDidShowNotification";
NSNotificationName const FDDToastWillDismissNotification = @"FDDToastWillDismissNotification";
NSNotificationName const FDDToastDidDismissNotification  = @"FDDToastDidDismissNotification";

/**
 toast的style
 
 - FDDToastStyleText: 纯文本toast
 - FDDToastStyleImageText: 图文toast
 - FDDToastStyleZan: 赞👍
 */
typedef NS_ENUM(NSUInteger, FDDToastStyle) {
    FDDToastStyleText,
    FDDToastStyleImageText,
    FDDToastStyleZan
};

// toast初始背景颜色
static UIColor *FDDToastInitialBackgroundColor;
// toast初始文本颜色
static UIColor *FDDToastInitialTextColor;
// toast初始展示时间
static NSTimeInterval FDDToastInitialDuration;
// toast初始消失时间
static NSTimeInterval FDDToastInitialFadeDuration;

// toast默认背景颜色
static UIColor *FDDToastDefaultBackgroundColor;
// toast默认文本颜色
static UIColor *FDDToastDefaultTextColor;
// toast默认展示时间
static NSTimeInterval FDDToastDefaultDuration;
// toast默认消失时间
static NSTimeInterval FDDToastDefaultFadeDuration;

@interface FDDToast ()

@property (nonatomic, strong) UILabel      *messageLabel;
@property (nonatomic, strong) UIImageView  *imageView;

@end

@implementation FDDToast



+ (FDDToast*)sharedView {
    static dispatch_once_t once;
    
    static FDDToast *sharedView;
#if !defined(SV_APP_EXTENSIONS)
    dispatch_once(&once, ^{
        sharedView = [[self alloc] init];
        
    });
#else
    dispatch_once(&once, ^{
        sharedView = [[self alloc] init];
        
    });
#endif
    return sharedView;
}


#pragma mark - Initial

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //========== 设置初始值 ==========//
        FDDToastInitialBackgroundColor = kHexColor(@"#1D1D1E");
        FDDToastInitialTextColor       = [UIColor whiteColor];
        FDDToastInitialDuration     = 2;
        FDDToastInitialFadeDuration = 0.3;
        
        //========== 设置初始默认值 ==========//
        FDDToastDefaultBackgroundColor = FDDToastInitialBackgroundColor;
        FDDToastDefaultTextColor       = FDDToastInitialTextColor;
        FDDToastDefaultDuration        = FDDToastInitialDuration;
        FDDToastDefaultFadeDuration    = FDDToastInitialFadeDuration;
    });
}

// 初始化方法里可以对各种toast的一致属性进行统一设置
- (instancetype)init {
    if (self = [super init]) {
        // 创建subView
        self.messageLabel = [[UILabel alloc] init];
        self.imageView    = [[UIImageView alloc] init];
        [self addSubview:self.messageLabel];
        [self addSubview:self.imageView];
        
        // toast的一致属性
        self.layer.cornerRadius = 8;
        self.backgroundColor = FDDToastDefaultBackgroundColor ?: FDDToastInitialBackgroundColor;
        self.messageLabel.textColor = FDDToastDefaultTextColor ?: FDDToastInitialTextColor;
        self.messageLabel.numberOfLines = 1;
        self.messageLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

#pragma mark - UI

/** 纯文本toast */
- (void)p_setupTextToastWithMessage:(NSString *)message {
    self.messageLabel.text = message;
    self.messageLabel.font = [UIFont boldSystemFontOfSize:15];
    
    // 设置toast的约束
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.superview);
//        make.bottom.mas_offset(-100);
        make.center.mas_equalTo(self.superview);

        make.top.left.mas_equalTo(self.messageLabel).mas_offset(-20);
        make.bottom.right.mas_equalTo(self.messageLabel).mas_offset(20);
    }];
    
    // 设置label的约束
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_lessThanOrEqualTo(140);
        make.center.mas_equalTo(self.messageLabel.superview);
    }];
}

/** 图文toast */
- (void)p_setupImageTextToastWithMessage:(NSString *)message image:(NSString *)imageName {
    // label
    self.messageLabel.text = message;
    self.messageLabel.font = [UIFont systemFontOfSize:13];
    
//    self.backgroundColor = [UIColor systemPinkColor];
    // imageView
    self.imageView.image = [UIImage imageNamed:imageName];
    
    // 设置toast的约束
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.mas_equalTo(self.superview);
        make.top.mas_equalTo(self.imageView).mas_offset(-16);
        make.bottom.right.mas_equalTo(self.messageLabel).mas_offset(10);
    }];
    
    // 设置imageView的约束
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.mas_centerY);
        make.left.mas_equalTo(12);
        make.size.mas_equalTo(CGSizeMake(16, 18));
    }];
    
    // 设置label的约束
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.mas_lessThanOrEqualTo(200);
//        make.height.mas_equalTo(20);
        make.centerY.mas_equalTo(self);
        make.left.mas_equalTo(self.imageView.mas_right).mas_offset(8);
    }];
}

/** 赞 */
- (void)p_setupZanToast {
    self.backgroundColor = [UIColor whiteColor];
    self.imageView.image = [UIImage imageNamed:@"zan"];
    self.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2-20, [UIScreen mainScreen].bounds.size.height/2-20, 40, 40);
    self.imageView.frame = self.bounds;
    // 简单动画
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    animation.values = @[@1.5, @1.0];
    animation.duration = 0.3;
    animation.calculationMode = kCAAnimationCubic;
    [self.layer addAnimation:animation forKey:@"transform.scale"];
}

/** 根据传入的style创建不同的toast */
- (void)p_setupWithMessage:(NSString *)message image:(NSString *)imageName style:(FDDToastStyle)style {
    switch (style) {
        case FDDToastStyleText:
        {
            // 纯文本toast
            [self p_setupTextToastWithMessage:message];
        }
            break;
            
        case FDDToastStyleImageText:
        {
            // 图文toast
            [self p_setupImageTextToastWithMessage:message image:imageName];
        }
            break;
        case FDDToastStyleZan:
        {
            // 赞👍
            [self p_setupZanToast];
        }
    }
}

#pragma mark - show toast

/** 纯文本toast */
+ (void)showWithMessage:(NSString *)message {
    [FDDToast p_showWithMessage:message image:nil duration:FDDToastDefaultDuration style:FDDToastStyleText];
}

+ (void)showWithMessage:(NSString *)message duration:(NSTimeInterval)duration {
    [FDDToast p_showWithMessage:message image:nil duration:duration style:FDDToastStyleText];
}

/** 图文toast */
+ (void)showErrorWithMessage:(NSString *)message  {
    [FDDToast p_showWithMessage:message image:@"icon_alert" duration:FDDToastDefaultDuration style:FDDToastStyleImageText];
}

+ (void)showWithMessage:(NSString *)message image:(NSString *)imageName duration:(NSTimeInterval)duration {
    [FDDToast p_showWithMessage:message image:imageName duration:duration style:FDDToastStyleImageText];
}

/** 赞 */
+ (void)showZan {
    [FDDToast p_showWithMessage:nil image:nil duration:FDDToastDefaultDuration style:FDDToastStyleZan];
}

+ (void)showZanWithDuration:(NSTimeInterval)duration {
    [FDDToast p_showWithMessage:nil image:nil duration:duration style:FDDToastStyleZan];
}

/** 全能show方法 */
+ (void)p_showWithMessage:(NSString *)message image:(NSString *)imageName duration:(NSTimeInterval)duration style:(FDDToastStyle)style {
    // 切换到主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        // 将要展示
        [[NSNotificationCenter defaultCenter] postNotificationName:FDDToastWillShowNotification object:nil];
        FDDToast *toast = [FDDToast sharedView];
        toast.alpha = 1;

        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
         [delegate.window addSubview:toast];        
        [toast p_setupWithMessage:message image:imageName style:style];
        // 已经展示
        [[NSNotificationCenter defaultCenter] postNotificationName:FDDToastDidShowNotification object:nil];
        // 指定时间移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 将要消失
            [[NSNotificationCenter defaultCenter] postNotificationName:FDDToastWillDismissNotification object:nil];
            [UIView animateWithDuration:FDDToastDefaultFadeDuration animations:^{
                toast.alpha = 0;
            } completion:^(BOOL finished) {
                [toast removeFromSuperview];
                // 已经消失
                [[NSNotificationCenter defaultCenter] postNotificationName:FDDToastDidDismissNotification object:nil];
            }];
        });
    });
}

#pragma mark - 设置默认值

/** 设置toast的默认背景颜色 */
+ (void)setDefaultBackgroundColor:(UIColor *)defaultBackgroundColor {
    FDDToastDefaultBackgroundColor = defaultBackgroundColor;
}

/** 设置默认字体颜色 */
+ (void)setDefaultTextColor:(UIColor *)defaultTextColor {
    FDDToastDefaultTextColor = defaultTextColor;
}

/** 设置toast展示的默认时间，未设置为2秒 */
+ (void)setDefaultDuration:(NSTimeInterval)defaultDuration {
    FDDToastDefaultDuration = defaultDuration;
}

/** 设置toast消失的默认时间，未设置为0.3秒 */
+ (void)setDefaultFadeDuration:(NSTimeInterval)defaultFadeDuration {
    FDDToastDefaultFadeDuration = defaultFadeDuration;
}

#pragma mark - 重置为初始状态

/** 重置为初始状态（这个方法适用于某次改变默认值后又想改回去的情况） */
+ (void)reset {
    FDDToastDefaultBackgroundColor = FDDToastInitialBackgroundColor;
    FDDToastDefaultTextColor       = FDDToastInitialTextColor;
    FDDToastDefaultDuration        = FDDToastInitialDuration;
    FDDToastDefaultFadeDuration    = FDDToastInitialFadeDuration;
}

@end
